package com.example.motion.service.impl;

import com.example.motion.config.vx.WXCore;
import com.example.motion.dao.MotionRecordMapper;
import com.example.motion.model.MotionActivityDate;
import com.example.motion.model.MotionRecord;
import com.example.motion.service.IMotionActivityDateService;
import com.example.motion.service.MotionRecordService;
import com.example.motion.vo.MotionRecodeTopVo;
import com.example.motion.vo.MotionRecordVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class MotionRecordServiceImpl implements MotionRecordService {


    /**
     * 多少布兑换1公里
     */
    @Value("${motion.stepKilo}")
    private int stepKilo;
    /**
     * 每天兑换最大步数
     */
    @Value("${motion.maxStep}")
    private int maxStep;

    /**
     * 兑换成功
     */
    private static final Integer useCode_0 = 0;
    /**
     * 兑换失败，超过最大兑换限制
     */
    private static final Integer useCode_1 = 1;

    @Autowired
    private MotionRecordMapper motionRecordMapper;

    @Autowired
    private IMotionActivityDateService iMotionActivityDateService;

    private DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

    /**
     * 记录步数
     * @param appId
     * @param encryptedData
     * @param sessionKey
     * @param iv
     * @param openid
     */
    @Override
    public MotionRecord motionRecord(String appId, String encryptedData, String sessionKey, String iv, String openid) {
        // 获取今天的步数
        String now = dateFormat.format(new Date());
        MotionRecord motionRecord = motionRecordMapper.getStepByOpenidAndDate(openid, now);
        // 解析微信步数
        String jsonData = WXCore.decrypt(appId, encryptedData, sessionKey, iv);
        JSONObject jsonTest = JSONObject.fromObject(jsonData);
        JSONArray jsonArray = jsonTest.getJSONArray("stepInfoList");
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            // 运动时间
            long timestamp = jsonObject.getLong("timestamp");
            Date date = new Date(timestamp * 1000);
            String runDate = dateFormat.format(date);
            // 微信步数
            int step = jsonObject.getInt("step");
            // 只处理当天数据
            if (runDate.equals(now)) {
                if (motionRecord != null) {
                    // 更新
                    motionRecord.setStepTotal(step);
                    motionRecord.setStepNotUse((step - motionRecord.getStepUse()));
                    motionRecordMapper.updateRecord(motionRecord);
                } else {
                    // 新增
                    motionRecord = new MotionRecord();
                    motionRecord.setOpenid(openid);
                    motionRecord.setMotionTime(new Date());
                    motionRecord.setStepTotal(step);
                    motionRecord.setStepNotUse(step);
                    motionRecord.setStepUse(0);
                    motionRecord.setKilometre(0);
                    motionRecordMapper.addRecord(motionRecord);
                }
            }
        }
        return motionRecord;
    }

    @Override
    public MotionRecordVo exchangeStep(String openid) {
        Map<String, Object> result = new HashMap<>(1);
        // 获取今天的步数信息
        String now = dateFormat.format(new Date());
        MotionRecord motionRecord = motionRecordMapper.getStepByOpenidAndDate(openid, now);
        // 计算当天兑换步数，超过一定步数后，不允许兑换
        // 或者是最大兑换步数-已兑换的步数 < 兑换比例
        if (motionRecord.getStepUse() >= maxStep || (maxStep - motionRecord.getStepUse()) < stepKilo) {
            MotionRecordVo motionRecordVo = getStep(openid);
            motionRecordVo.setUseCode(useCode_1);
            return motionRecordVo;
        }
        // 计算公里数
        // 未兑换的步数
        int stepNotUse = motionRecord.getStepNotUse();
        // 可用兑换的步数
        int currentMaxStep = maxStep - motionRecord.getStepUse();
        // 为兑换步数大于等于可用兑换步数，则赋值兑换所有可兑换步数
        if (stepNotUse >= currentMaxStep) {
            stepNotUse = currentMaxStep;
        }
        // 1668步为1公里
        int killo = stepNotUse / stepKilo;
        // 不够1公里的步数
        int notUseStep = stepNotUse % stepKilo + (motionRecord.getStepNotUse() - stepNotUse);
        // 已兑换步数
        int useStep = motionRecord.getStepTotal() - notUseStep;
        motionRecord.setStepUse(useStep);
        motionRecord.setStepNotUse(motionRecord.getStepTotal() - useStep);
        motionRecord.setKilometre(killo + motionRecord.getKilometre());
        motionRecordMapper.updateRecord(motionRecord);
        // 获取最新首页信息
        MotionRecordVo motionRecordVo = getStep(openid);
        motionRecordVo.setUseCode(useCode_0);
        return motionRecordVo;
    }


    @Override
    public MotionRecordVo getStep(String openid) {
        // 获取当天数据
        String dateTime = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        // 获取当日信息
        MotionRecord motionRecord = motionRecordMapper.getStepByOpenidAndDate(openid, dateTime);
        MotionRecordVo motionRecordVo = new MotionRecordVo();
        if (motionRecord != null) {
            BeanUtils.copyProperties(motionRecord, motionRecordVo);
        }
        // 获取活动期限
        MotionActivityDate motionActivityDate = iMotionActivityDateService.getActivityDate();
        // 获取用户在活动期间参加活动天数、公里数、排名
        Map<String, Object> totalKiloByOpenid = motionRecordMapper.getTotalKiloByOpenid(openid,
                motionActivityDate.getStartDate(), motionActivityDate.getEndDate());
        if (CollectionUtils.isEmpty(totalKiloByOpenid)) {
            totalKiloByOpenid.put("kilometreTotal", 0);
            totalKiloByOpenid.put("stepDay", 0);
        }
        // 活动期间总公里数
        motionRecordVo.setKilometreTotal(
                Integer.parseInt(
                        StringUtils.isEmpty(totalKiloByOpenid.get("kilometreTotal"))? "0" : totalKiloByOpenid.get("kilometreTotal").toString()
                )
        );
        // 参加活动天数
        motionRecordVo.setStepDay(
                Integer.parseInt(StringUtils.isEmpty(totalKiloByOpenid.get("stepDay"))? "0" : totalKiloByOpenid.get("stepDay").toString()
                )
        );
        // // 获取排名
        // 获取所有人排名之后，过滤当前openid，得到排名号
        List<MotionRecodeTopVo> motionRecodeTopVos = motionRecordMapper.getPersonTop(
                motionActivityDate.getStartDate(),
                motionActivityDate.getEndDate(), null);
        motionRecodeTopVos = motionRecodeTopVos.stream().filter(motionRecodeTopVo ->
            openid.equals(motionRecodeTopVo.getOpenid())).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(motionRecodeTopVos)) {
            motionRecordVo.setRanking(motionRecodeTopVos.get(0).getTopNo());
        }
        //大约走路20步消耗1卡路里
       /* String personalCalorie = (personalStep / 20) + "";
        String teamCalorie = (teamStep / 20) + "";
        String personalCalorieTotal = (personalStepTotal / 20) + "";
        String personalDays = personalDay + "天";
        String teamCount = teamPersonalCount +"人";*/
        return motionRecordVo;
    }

    /***
     * @description 获取总步数
     * @param:
     * @return: java.util.List<java.util.Map < java.lang.String, java.lang.Object>>
     * @author wangzq
     * @date 2023/5/4 8:43
     */
    @Override
    public Map<String, Object> getTotal() {
        // 获取活动时间
        MotionActivityDate motionActivityDate = iMotionActivityDateService.getActivityDate();
        Map<String, Object> total = motionRecordMapper.getTotal(motionActivityDate.getStartDate(),
                motionActivityDate.getEndDate());
        return total;
    }


    @Override
    public PageInfo<MotionRecodeTopVo> getPersonTop(int pageNo, int pageSize, String officeCode) {
        // 获取活动时间
        MotionActivityDate motionActivityDate = iMotionActivityDateService.getActivityDate();
        PageHelper.startPage(pageNo, pageSize);
        // 获取活动排名
        List<MotionRecodeTopVo> personTop = motionRecordMapper.getPersonTop(motionActivityDate.getStartDate(),
                motionActivityDate.getEndDate(), officeCode);
        PageInfo<MotionRecodeTopVo> pageInfo = new PageInfo<>(personTop);
        return pageInfo;
    }

    @Override
    public List<MotionRecodeTopVo> getOfficeTop() {
        // 获取活动时间
        MotionActivityDate motionActivityDate = iMotionActivityDateService.getActivityDate();
        return motionRecordMapper.getOfficeTop(motionActivityDate.getStartDate(),
                motionActivityDate.getEndDate());
    }

    @Override
    public List<MotionRecodeTopVo> getOfficeTargetMileage() {
        // 获取活动时间
        MotionActivityDate motionActivityDate = iMotionActivityDateService.getActivityDate();
        return motionRecordMapper.getOfficeTargetMileage(motionActivityDate.getStartDate(),
                motionActivityDate.getEndDate());
    }

    /**
     * 获取活动参与总人数
     */
    @Override
    public int getAcitivityPersonNum() {
        MotionActivityDate motionActivityDate = iMotionActivityDateService.getActivityDate();
        return motionRecordMapper.getAcitivityPersonNum(motionActivityDate.getStartDate(), motionActivityDate.getEndDate());
    }
}
